package com.zhuliyou.ai.service;


import com.alibaba.fastjson.JSONObject;
import com.zhuliyou.ai.config.CustomConfig;
import com.zhuliyou.ai.util.Base64Util;
import com.zhuliyou.ai.util.FileUtil;
import com.zhuliyou.ai.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


/**
 * @author zhuliyou
 * @date 2021/06/02
 */
@Service
public class FaceMerge {

    @Autowired
    private AuthService authService;

    @Autowired
    private CustomConfig customConfig;


    /**
     * 此方法会以第一张图片为基础,将第二张图片的脸融合到第一张图片上
     *
     * @return {@link String}
     */
    public String faceMerge(File file1,File file2) {
        // 请求url
        String url = customConfig.getUrl();
        try {
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> imageTemplateMap = new HashMap<>();
            imageTemplateMap.put("image", Base64Util.encode(FileUtil.readFileByBytes(file1)));
            imageTemplateMap.put("image_type", "BASE64");
            imageTemplateMap.put("quality_control", "NONE");
            map.put("image_template", imageTemplateMap);
            Map<String, Object> imageTargetMap = new HashMap<>();
            imageTargetMap.put("image", Base64Util.encode(FileUtil.readFileByBytes(file2)));
            imageTargetMap.put("image_type", "BASE64");
            imageTargetMap.put("quality_control", "NONE");
            map.put("image_target", imageTargetMap);
            String param = JSONObject.toJSONString(map);
            String accessToken = authService.getAuth();
            String result = HttpUtil.post(url, accessToken, "application/json", param);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject result1 = jsonObject.getJSONObject("result");
            return result1.getString("merge_image");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}